package com.carpedil.smvc.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.carpedil.smvc.po.User;
import com.carpedil.smvc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/** @author Administrator */
@Controller
@RequestMapping("/user")
public class UserController {
  @Autowired private UserService userService;

  @RequestMapping("/{name}")
  public String getUsers1(@PathVariable("name") String name, HttpServletRequest request) {
    System.out.println(name);
    IPage<User> page = userService.getUsersByPage(1, 10);
    page.getRecords().forEach(System.out::println);
    request.setAttribute("users", page.getRecords());
    return "users";
  }

  @RequestMapping("/role/{id}")
  public String getUsersByRoleId(@PathVariable("id") Integer id, HttpServletRequest request) {
    // 通过路径传值使用@PathVariable
    System.out.println(id);
    IPage<User> page = userService.getUsersByPageParam(1, 10, id);
    request.setAttribute("users", page.getRecords());
    return "users";
  }

  @RequestMapping("/2")
  public void getUsers2(
      HttpServletRequest request, HttpServletResponse response, HttpSession session)
      throws ServletException, IOException {
    IPage<User> page = userService.getUsersByPage(1, 10);
    request.setAttribute("users", page.getRecords());
    session.setAttribute("users", page.getRecords());
    request.getRequestDispatcher("users").forward(request, response);
  }

  @RequestMapping("/3")
  public ModelAndView getUsers3() {
    IPage<User> page = userService.getUsersByPage(1, 10);
    ModelAndView mv = new ModelAndView();
    mv.setViewName("users");
    mv.addObject("mv", page.getRecords());
    return mv;
  }

  @RequestMapping("/4")
  public String getUsers4(ModelMap mp) {
    IPage<User> page = userService.getUsersByPage(1, 10);
    mp.addAttribute("mp", page.getRecords());
    return "users";
  }
}
